<!-- Schedule Details -->
<!-- Author: Edwin -->
<template>
  <el-dialog :visible.sync="dialogStatus"
             :show-close="true"
             :close-on-click-modal="true"
             :append-to-body="true"
             :destroy-on-close="true"
             @close="beforeDialogClose"
             width="650px">
    <div>

      <el-row :gutter="20"
              style="display:flex;align-items:center;margin-bottom:10px;">
        <el-col :span="6"
                style="text-align:right;">{{ i18nT('custom.workSchedule.templateTitle') }}</el-col>
        <el-col :span="18">
          <el-select v-model="selectedTemplate"
                     style="width:100%;height:30px;"
                     @change='templateChange'
                     clearable
                     :filterable="true"
                     :default-first-option="true"
                     :placeholder="i18nT('custom.workSchedule.selectTemplate')">
            <el-option v-for="item in templateList"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id">
            </el-option>
          </el-select>
        </el-col>
      </el-row>

      <el-row :gutter="24"
              style="display:flex;align-items:center;margin-bottom:10px;">
        <el-col :span="6"
                style="text-align:right;">{{ i18nT('custom.workSchedule.timezoneTitle') }}</el-col>
        <el-col :span="14">
          <el-select v-model="selectedTimezone"
                     style="width:100%;height:30px;"
                     :filterable="true"
                     :default-first-option="true"
                     :placeholder="i18nT('custom.workSchedule.selectTimezone')">
            <el-option v-for="item in timezoneListData"
                       :key="item"
                       :label="item"
                       :value="item">
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-tag v-show="selectedTimezone">{{'UTC'+computedTimeOffset(selectedTimezone)}}</el-tag>
        </el-col>
      </el-row>
      <el-row :gutter="20"
              style="height:30px;line-height:30px;fontWeight:bold;">
        <el-col :span="6"
                style="text-align:right;">{{ i18nT('custom.workSchedule.templatetime')}}</el-col>
        <el-col :span="9"
                style="text-align:center;">{{ i18nT('custom.workSchedule.from') }}</el-col>
        <el-col :span="9"
                style="text-align:center;">{{ i18nT('custom.workSchedule.to') }}</el-col>
      </el-row>
      <el-row :gutter="20"
              style="display:flex;align-items:center;margin-bottom:15px;">
        <el-col :span="6"></el-col>
        <el-col :span="9">
          <el-time-picker v-model="templateBeginTime"
                          size="small"
                          style="width:80%;"
                          format="HH:mm"
                          @focus="setBeginTime"
                          :picker-options="{
                            selectableRange: `00:00:00 - ${templateEndTime?templateEndTime+':00':'23:59:59'}`
                          }"
                          value-format="HH:mm"
                          :placeholder="i18nT('custom.workSchedule.from')">
          </el-time-picker>
        </el-col>
        <el-col :span="9">
          <el-time-picker v-model="templateEndTime"
                          size="small"
                          style="width:80%;"
                          format="HH:mm"
                          :picker-options="{
                            selectableRange: `${templateBeginTime?templateBeginTime+':00':'00:00:00'} - 23:59:59`
                          }"
                          @focus="setEndTime"
                          value-format="HH:mm"
                          :placeholder="i18nT('custom.workSchedule.to')">
          </el-time-picker>
        </el-col>
      </el-row>
      <el-row :gutter="20"
              style="height:30px;line-height:30px;fontWeight:bold;">
        <el-col :span="6"
                style="text-align:right;">{{ i18nT('custom.workSchedule.day') }}</el-col>
        <!-- <el-col :span="9"
                style="text-align:center;">{{ i18nT('custom.workSchedule.from') }}</el-col>
        <el-col :span="9"
                style="text-align:center;">{{ i18nT('custom.workSchedule.to') }}</el-col> -->
      </el-row>
      <el-row v-for="(item,index) in scheduleData"
              :key="index"
              :gutter="20"
              style="display:flex;align-items:center;margin-bottom:15px;">
        <el-col :span="6"
                style="text-align:right;">{{ item.dayOfWeek }}</el-col>
        <el-col :span="9">
          <el-time-picker v-model="item.beginTime"
                          size="small"
                          style="width:80%;"
                          format="HH:mm"
                          :picker-options="{
                            selectableRange: `00:00:00 - ${item.endTime?item.endTime+':00':'23:59:59'}`
                          }"
                          @focus="setItemBeginTime(item)"
                          value-format="HH:mm"
                          :placeholder="i18nT('custom.workSchedule.from')">
          </el-time-picker>
        </el-col>
        <el-col :span="9">
          <el-time-picker v-model="item.endTime"
                          size="small"
                          style="width:80%;"
                          format="HH:mm"
                          :picker-options="{
                            selectableRange: `${item.beginTime?item.beginTime+':00':'00:00:00'} - 23:59:59`
                          }"
                          @focus="setItemEndTime(item)"
                          value-format="HH:mm"
                          :placeholder="i18nT('custom.workSchedule.to')">
          </el-time-picker>
          <el-tooltip effect="dark" :open-delay="1000"  placement="top"  content="Schedule Unify">
              <i class="cuifont icon_schedule_unify" style="margin-left: 10px;" @click="setTemplateTime(item)"></i>
          </el-tooltip>
          </el-col>
      </el-row>
    </div>
    <div slot="footer">
      <el-button size="mini"
                 style="color:#999;fontWeight:bold;"
                 @click="closeDialog">{{ i18nT('custom.workSchedule.cancel') }}</el-button>
      <el-button size="mini"
                 type="primary"
                 style="fontWeight:bold;"
                 :loading="saveLoading"
                 @click="clickSaveBtn">{{ i18nT('custom.workSchedule.confirm') }}</el-button>
    </div>
  </el-dialog>
</template>

<script>
import moment from 'moment'
import { BridgeComponent } from './bridgeComponent'
import i18n from '@/i18n'
import { TimeZoneNameList } from '@/utils'
import { clearLoginInfo, loginSourcePathURL } from '@/utils'
import { useMsal, msalInstance } from '@/components/storybook/hooks/useMsal'

const { logoutPopup } = useMsal()
export default {
  props: {
    setType: {
      type: String,
      default: 'save-batch'
    },
    addTemplateDialog: {
      type: Boolean,
      default: false
    },
    tenantCode: {
      type: String,
      default: ''
    },
    userId: {
      type: String,
      default: ''
    },
    username: {
      type: String,
      default: ''
    },
    timezoneFull: {
      type: String,
      default: ''
    },
    timezoneName: {
      type: String,
      default: ''
    },
    timezoneOffset: {
      type: String,
      default: ''
    },
    workScheduleList: {
      type: Array,
      default: () => []
    },
    workSchedule: {
      type: Object,
      default: () => { return {} }
    },
    tenantUserId: {
      type: String,
      default: ''
    },
    batchData: {
      type: Array,
      default: () => []
    }
  },
  data () {
    return {
      scheduleData: [],
      selectedDate: null,
      timezoneFields: {},
      timezoneListData: TimeZoneNameList(),
      selectedTimezone: null,
      saveLoading: false,
      selectedTemplate: null,
      templateList: [],
      changeParams: null,
      templateBeginTime: '08:00',
      templateEndTime: '17:00'
    }
  },
  watch: {
    addTemplateDialog (val) {
      if (val) {
        // Object.assign(this.scheduleData, this.workScheduleList)
        this.scheduleData = JSON.parse(JSON.stringify(this.workScheduleList))
        this.selectedTimezone = this.timezoneFull ? this.timezoneFull : this.$store.state.user.tenantTimezoneId
        this.getTemplateList()
      } else {
        // Object.assign(this.$data, this.$options.data())
      }
    }
    // dialogStatus (val) {
    //   if (!val) {

    //   }
    // }
  },
  computed: {
    dialogStatus: {
      get () {
        return this.addTemplateDialog
      },
      set (val) {
        if (!val) {
          this.closeDialog()
        }
      }
    }
  },
  methods: {
    computedTimeOffset (data) {
      try {
        if (data) {
          return moment.tz(data).format('Z')
        }
      } catch (error) {
        return ''
      }
    },
    templateChange (templateId) {
      if (!templateId) {
        this.scheduleData = JSON.parse(JSON.stringify(this.workScheduleList))
        this.selectedTimezone = this.timezoneFull
        return false
      }
      const tempInfo = this.templateList.find(e => e.id === templateId)
      this.selectedTimezone = tempInfo.template.timezone
      // this.scheduleData.dayOfWeek = tempInfo.template.scheduleData.dayOfWeek
      // this.scheduleData.beginTime = tempInfo.template.scheduleData.beginTime
      // this.scheduleData.endTime = tempInfo.template.scheduleData.endTime
      tempInfo.template.scheduleData.map(e => {
        this.scheduleData.map(o => {
          if (e.dayOfWeek === o.dayOfWeek) {
            o.beginTime = e.beginTime
            o.endTime = e.endTime
          }
        })
      })
    },
    getTemplateList () {
      const params = {
        type: 'work_schedule'
        // tenantCode: this.$store.state.user.tenantCode
        //   current: currentPage || this.pageOptions.currentPage,
        //   size: this.pageOptions.pageSize
      }
      this.$interface.schedule.getTemplateListApi(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.templateList = res.data.map(e => {
            e.template = JSON.parse(e.template)
            return e
          })
        })
        .catch(() => { })
    },
    beforeDialogClose () {
      Object.assign(this.$data, this.$options.data())
      // this.scheduleData = []
      // this.selectedTimezone = null
    },
    i18nT (key) {
      return i18n.t(key)
    },
    clickSaveBtn () {
      switch (this.setType) {
        case 'save-batch':
          this.saveSchedule()
          break
        case 'save-batch-users':
          this.batchSaveSchedule()
          break
        default:
          break
      }
    },
    setTemplateTime (data) {
      data.beginTime = this.templateBeginTime
      data.endTime = this.templateEndTime
      this.$forceUpdate()
    },
    setBeginTime () {
      !this.templateBeginTime && (this.templateBeginTime = '00:00')
    },
    setEndTime () {
      !this.templateEndTime && (this.templateEndTime = '00:00')
    },
    setItemBeginTime (data) {
      !data.beginTime && (data.beginTime = '00:00')
    },
    setItemEndTime (data) {
      !data.endTime && (data.endTime = '00:00')
    },
    batchSaveSchedule () {
      this.$confirm(
        this.$t('prompt.para', {
          handle: this.$t('custom.workSchedule.confirmchangetimezone')
        }),
        this.$t('prompt.title'),
        {
          confirmButtonText: this.$t('confirm'),
          cancelButtonText: this.$t('cancel'),
          type: 'warning'
        }
      )
        .then(() => {
          this.saveLoading = true
          if (!this.selectedTimezone) {
            this.$message.error('Please select time zone.')
            this.saveLoading = false
            return false
          }
          const params = () => {
            const timeZoneShortName = moment.tz(this.selectedTimezone).format('zz')
            let timezoneName = null
            var isNumber = /^[a-zA-Z]+$/.test(timeZoneShortName)
            if (!isNumber) {
              timezoneName = 'UTC' + timeZoneShortName
            } else {
              timezoneName = timeZoneShortName
            }
            return this.batchData.map(item => {
              item.timezoneFull = this.selectedTimezone
              item.timezoneOffset = moment.tz(this.selectedTimezone).format('Z')
              item.timezoneName = timezoneName
              item.workScheduleList.forEach(workScheduleItem => {
                const matchSchedule = this.scheduleData.find((element) => (element.dayOfWeek === workScheduleItem.dayOfWeek))

                if (matchSchedule) {
                  workScheduleItem.beginTime = matchSchedule.beginTime
                  workScheduleItem.endTime = matchSchedule.endTime
                }
              })

              return item
            })
          }
          this.changeParams = null
          this.changeParams = params()
          this.$interface.schedule.saveBatchUsersApi(params())
            .then(({ data: res }) => {
              this.saveLoading = false
              if (res.code !== 0) {
                return this.$message.error(res.msg)
              }
              if (res.data) {
                this.closeDialog()
                this.$message.success('Success.')
                BridgeComponent.$emit('updateScheduleList')
              }
            })
            .catch(() => {
              this.saveLoading = false
            })

          for (let index = 0; index < this.changeParams.length; index++) {
            const element = this.changeParams[index]
            const params = { userId: element.userId }           
            if (params.userId === this.$store.state.user.id) {
              this.logoutHandle()
            } else {
              this.$interface.system.delUserRedisInfoApi(params)
            }
          }
        })
    },
    saveSchedule () {
      // TODO need to add tips
      this.saveLoading = true
      if (!this.selectedTimezone) {
        this.$message.error('Please select time zone.')
        this.saveLoading = false
        return false
      }
      const timeZoneShortName = moment.tz(this.selectedTimezone).format('zz')
      let timezoneName = null
      var isNumber = /^[a-zA-Z]+$/.test(timeZoneShortName)
      if (!isNumber) {
        timezoneName = 'UTC' + timeZoneShortName
      } else {
        timezoneName = timeZoneShortName
      }
      this.changeParams = null
      const params = {
        tenantCode: this.tenantCode,
        userId: this.userId,
        username: this.username,
        timezoneFull: this.selectedTimezone,
        timezoneName: timezoneName,
        timezoneOffset: moment.tz(this.selectedTimezone).format('Z'),
        workScheduleList: this.scheduleData,
        workSchedule: this.workSchedule,
        tenantUserId: this.tenantUserId
      }
      this.changeParams = params.userId
      this.$interface.schedule.saveBatchApi(params)
        .then(({ data: res }) => {
          this.saveLoading = false
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          if (res.data) {
            this.closeDialog()
            this.$message.success('Success.')
            BridgeComponent.$emit('updateScheduleList')
          }
          if(this.changeParams === this.$store.state.user.id){
            this.logoutHandle()
          }else{
            const params = { userId: this.changeParams }
            this.$interface.system.delUserRedisInfoApi(params)
          }
        })
        .catch(() => {
          this.saveLoading = false
        })
    },
    closeDialog () {
      this.$emit('closeDialog')
    },
    async logoutHandle() {
      try {
        const { userLogoutApi } = this.$interface.system
        const { data: response } = await userLogoutApi()
        if (response.code !== 0) {
          throw response.msg
        }
        this.$store.state.contentTabs = []
        let temp = loginSourcePathURL()
        if (this.$store.state.user.microsoftId) {
          const request={account: msalInstance.getAccountByHomeId(localStorage.getItem('homeAccountId')),onRedirectNavigate: ()=>clearLoginInfo()}
          await logoutPopup(request)
          sessionStorage.setItem('redirectLoginUrl', `/${temp}`)
        } else {
          clearLoginInfo()
          this.$router.push(`/${temp}`, () => {
            this.$store.state.permission.routes = []
            sessionStorage.setItem(
              'redirectLoginUrl',
              `/${temp}`
            )
          })
        }
      } catch (error) {}
    }
  }
}
</script>

<style scoped>
</style>
